package top.yuyufeng.ticketassistant.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.yuyufeng.ticketassistant.orm.ServiceTrainDTO;
import top.yuyufeng.ticketassistant.utils.HttpUtils;
import top.yuyufeng.ticketassistant.utils.MyDateUtils;
import top.yuyufeng.ticketassistant.utils.StationUtil;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yuyufeng
 * @date 2018/1/15
 */
public class TrainServiceV1 {
    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    public List<ServiceTrainDTO> SearchTrainList(String begin, String end, String trainDate) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,5000);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,5000);
        List<ServiceTrainDTO> list = new ArrayList<>();
       /* String trainDate = "2018-01-24";
        String begin = "杭州";
        String end = "上虞";*/
        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("leftTicketDTO.from_station_name", begin);
        bodys.put("leftTicketDTO.to_station_name", end);
        bodys.put("leftTicketDTO.from_station", StationUtil.getStationByStationName(begin).getStationCode());
        bodys.put("leftTicketDTO.to_station", StationUtil.getStationByStationName(end).getStationCode());
        bodys.put("leftTicketDTO.train_date", trainDate);
        bodys.put("leftTicketDTO.back_train_date", trainDate);
        bodys.put("flag", "dc");
        bodys.put("purpose_code", "ADULT");
        bodys.put("pre_step_flag", "index");
        String host = "https://kyfw.12306.cn";
        String path = "/otn/leftTicket/init";
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "*/*");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
        headers.put("Cache-Control", "no-cache");
        headers.put("Connection", "keep-alive");
        headers.put("Host", "kyfw.12306.cn");
        headers.put("If-Modified-Since", "0");
        headers.put("X-Requested-With", "XMLHttpRequest");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        headers.put("Referer", "https://kyfw.12306.cn/otn/index/init");
        headers.put("Origin", "https://kyfw.12306.cn");
//        HttpResponse response = HttpUtils.doPost(host,path,"POST",headers,null,bodys);
        HttpPost httpPost = new HttpPost(host + path);
        for (Map.Entry<String, String> e : headers.entrySet()) {
            httpPost.addHeader(e.getKey(), e.getValue());
        }
        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.setEntity(formEntity);
        }

        HttpUtils.sslClient(httpClient);
        LOG.info("开始爬取Cookie：" + host + path);
       
        HttpResponse response = httpClient.execute(httpPost);
        List<Cookie> cookies = httpClient.getCookieStore().getCookies();
//        System.out.println(result);

        String cookieHeader = "";
        for (Cookie cookie : cookies) {
//            System.out.println(cookie.getName() + " " + cookie.getValue());
            cookieHeader = cookieHeader + cookie.getName() + "=" + cookie.getValue() + ";";
        }
        LOG.info(cookieHeader);

        ////
        querys = new HashMap<>();
        host = "https://kyfw.12306.cn";
//        String path = "/otn/leftTicket/queryZ?leftTicketDTO.train_date="+trainDate+"&leftTicketDTO.from_station=SHH&leftTicketDTO.to_station=HZH&purpose_codes=ADULT";
        path = "/otn/leftTicket/queryZ?leftTicketDTO.train_date=" + trainDate + "&leftTicketDTO.from_station=" + StationUtil.getStationByStationName(begin).getStationCode() + "&leftTicketDTO.to_station=" + StationUtil.getStationByStationName(end).getStationCode() + "&purpose_codes=ADULT";
        headers = new HashMap<>();
        headers.put("Accept", "*/*");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
        headers.put("Cache-Control", "no-cache");
        headers.put("Connection", "keep-alive");
        headers.put("Host", "kyfw.12306.cn");
        headers.put("If-Modified-Since", "0");
        headers.put("X-Requested-With", "XMLHttpRequest");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        headers.put("Referer", "https://kyfw.12306.cn/otn/leftTicket/init");
        headers.put("Cookie", cookieHeader + "RAIL_EXPIRATION=1516267056210; RAIL_DEVICEID=fj5ZdCpMH5HoTrckAdFRErbRpYTg49D9vBa3dNHV_HE5Ts97VaMBGDq0gWGX7wPOWRSvdz2FYcgqoUOPZNPP2h9WoLu4ctlp2ShbGsW4ct8tCXSiJ3CdRHnJrwZV66FzzlRSaA-UhMvka5Wf0_LSSSx_Tp-MJ6YY; _jc_save_toDate=" + MyDateUtils.getTodayString() + "; _jc_save_wfdc_flag=dc; acw_tc=AQAAAHT6iWilrQwASy/ieu2uTh/aGtsd; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u676D%u5DDE%2CHZH; _jc_save_fromDate=" + trainDate);
//        headers.put("Cookie", "JSESSIONID=D1D591F34E4C63C52EA09EA27990AAF4; route=9036359bb8a8a461c164a04f8f50b252; BIGipServerotn=82838026.38945.0000; RAIL_EXPIRATION=1516267056210; RAIL_DEVICEID=fj5ZdCpMH5HoTrckAdFRErbRpYTg49D9vBa3dNHV_HE5Ts97VaMBGDq0gWGX7wPOWRSvdz2FYcgqoUOPZNPP2h9WoLu4ctlp2ShbGsW4ct8tCXSiJ3CdRHnJrwZV66FzzlRSaA-UhMvka5Wf0_LSSSx_Tp-MJ6YY; _jc_save_toDate=2018-01-15; _jc_save_wfdc_flag=dc; acw_tc=AQAAAHT6iWilrQwASy/ieu2uTh/aGtsd; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u676D%u5DDE%2CHZH; _jc_save_fromDate=2018-01-24");
        LOG.info("开始爬取：" + host + path);
        response = HttpUtils.doGet(host, path, "GET", headers, querys);
        String entity = EntityUtils.toString(response.getEntity());
        LOG.info(entity);
        JSONObject jsonObject = JSONObject.parseObject(entity);
        JSONObject jsonData = jsonObject.getJSONObject("data");
        String flag = jsonData.getString("flag");
        String map = jsonData.getString("map");
        String result = jsonData.getString("result");

//        System.out.println(flag);
//        System.out.println(map);
//        System.out.println(result);

        result = result.replaceAll("\\[", "");
        result = result.replaceAll("\\]", "");
        LOG.info("====开始显示车次列表====");
        String[] trainContents = result.split(",");
        for (int i = 0; i < trainContents.length; i++) {
            String trainContent = trainContents[i];
            trainContent = trainContent.replaceAll("\"", "");
//            System.out.println(trainContent);

            String[] trainParams = trainContent.split("\\|");
           /* for (String trainParam : trainParams) {
                System.out.println("+"+trainParam+"+");
            }*/
           if(trainParams.length < 30){
               continue;
           }
            ServiceTrainDTO trainDTO = new ServiceTrainDTO();
            trainDTO.key = trainParams[0];
            trainDTO.operate = trainParams[1];
            trainDTO.id = trainParams[2];
            trainDTO.trainNo = trainParams[3];
            trainDTO.startStation = trainParams[4];
            trainDTO.lastStation = trainParams[5];
            trainDTO.beginStation = trainParams[6];
            trainDTO.endStation = trainParams[7];
            trainDTO.beginTime = trainParams[8];      //发车时间
            trainDTO.endTime = trainParams[9];    //到达时间
            trainDTO.overTime = trainParams[10];    //历经时间
            trainDTO.p5 = trainParams[11];
            trainDTO.key2 = trainParams[12];
            trainDTO.date = trainParams[13];        //出发日期
            trainDTO.p6 = trainParams[14];
            trainDTO.p7 = trainParams[15];
            trainDTO.p8 = trainParams[16];
            trainDTO.p9 = trainParams[17];
            trainDTO.seatBD = trainParams[32];          //商务
            trainDTO.seat1 = trainParams[31];         //一等座
            trainDTO.seat2 = trainParams[30];        //二等座
            trainDTO.bedSoftHigh = trainParams[21];     //高级软卧
            trainDTO.bedSoft = trainParams[23];     //软卧
            trainDTO.bedMove = trainParams[33];     //动卧
            trainDTO.bedHard = trainParams[28];     //硬卧
            trainDTO.seatSoft = trainParams[24];
            trainDTO.seatHard = trainParams[29];    //
            trainDTO.seatNo = trainParams[26];
            trainDTO.seatOther = trainParams[27];
            list.add(trainDTO);
        }
        LOG.info("查询到车次数量：" + list.size());
        return list;
    }

    public static void main(String[] args) throws Exception {
        TrainService trainService = new TrainService();
        List<ServiceTrainDTO> list = trainService.SearchTrainList("杭州", "上海", "2018-02-01");
        for (ServiceTrainDTO serviceTrainDTO : list) {
            System.out.println(serviceTrainDTO);
        }
    }
}

